package com.example.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.log.InitLog;
import com.example.log.UpdateLog;
import com.example.pojo.Notice;
import com.example.mapper.NoticeMapper;
import com.example.pojo.PageBean;
import com.example.pojo.Result;
import com.example.service.INoticeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.vd.vo.NoticeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 公告表 服务实现类
 * </p>
 *
 * @author fzy'
 * @since 2024-08-08
 */
@Service
@Slf4j
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements INoticeService {

    public Result getNoticeList(PageBean pageBean, String keyword) {
        Long currentPage = pageBean.getCurrentPage();
        Long pageSize = pageBean.getPageSize();
        LambdaQueryWrapper<Notice> wrapper=new LambdaQueryWrapper<Notice>()
                .eq(Notice::getIsDeleted,0)
                .like(keyword!=null,Notice::getTitle,keyword)
                .orderByDesc(Notice::getUpdateTime);
        Page<Notice> page= new Page<>(currentPage, pageSize);
        page(page,wrapper);
        List<Notice> list = page.getRecords();
        return Result.succeed(list);
    }
    public Result deletedById(Long id) {
        /*boolean type = removeById(id);*/
        LambdaUpdateWrapper<Notice> wrapper=new LambdaUpdateWrapper<Notice>()
                .eq(Notice::getId,id)
                .set(Notice::getIsDeleted,1);
        boolean type = update(wrapper);
        return type ? Result.succeed() : Result.error();
    }
    @UpdateLog
    public Result updateByNotice(NoticeVo noticeVo) {
        Notice notice = BeanUtil.toBean(noticeVo, Notice.class);
        LambdaUpdateWrapper<Notice> updateWrapper = new LambdaUpdateWrapper<Notice>()
                .eq(Notice::getIsDeleted, 0)
                .eq(Notice::getId, notice.getId());
        log.info("Notice: {}",notice);
        boolean type = update(notice, updateWrapper);
        return type ? Result.succeed() : Result.error();
    }
    @InitLog
    public Result insertByNotice(NoticeVo noticeVo) {
        try {
            Notice notice = BeanUtil.toBean(noticeVo, Notice.class);
            notice.setId(null);
            System.out.println("Notice: "+notice);
            save(notice);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return Result.error("必要数据不完整,请检查后重试~");
        }
        return Result.succeed();
    }
}
